package org.example.dormsystem.service.impl;

import org.example.dormsystem.mapper.AdminMapper;
import org.example.dormsystem.mapper.ChangeRecordMapper;
import org.example.dormsystem.mapper.StudentMapper;
import org.example.dormsystem.pojo.Admin;
import org.example.dormsystem.pojo.AdminBoard;
import org.example.dormsystem.pojo.ChangeRecord;
import org.example.dormsystem.pojo.Student;
import org.example.dormsystem.service.AdminService;
import org.example.dormsystem.util.Md5Util;
import org.example.dormsystem.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    ChangeRecordMapper changeRecordMapper;

    @Override
    public Admin findAdminByUsername(String username) {

        Admin admin = adminMapper.findAdminByUsername(username);

        return admin;
    }

    @Override
    public boolean register(String username, String password) {
        try {
            String md5String = Md5Util.getMD5String(password);
            adminMapper.add(username,md5String);
        }catch (Exception e){
            System.out.println(e);
            return false;
        }

        return true;
    }

    @Override
    public void passCheck(Integer changeRecordId) {
        ChangeRecord changeRecord = adminMapper.findChangeRecordById(changeRecordId);
        Student student = new Student();
        student.setId(changeRecord.getStudentId());
        student.setAdminNumber(changeRecord.getAdminNumber());
        student.setBedNumber(changeRecord.getBedNumber());
        student.setDormitoryNumber(changeRecord.getDormitoryNumber());
        student.setStudentName(changeRecord.getStudentName());
        student.setTelNumber(changeRecord.getTelNumber());
        studentMapper.updateStudent(student);
        adminMapper.deleteRecord(changeRecordId);
    }

    @Override
    public void noPassCheck(Integer changeRecordId) {
        adminMapper.deleteRecord(changeRecordId);
    }

    @Override
    public void submit(String message) {
        Map<String,Object> map = ThreadLocalUtil.get();
        AdminBoard adminBoard = new AdminBoard();
        adminBoard.setMessage(message);
        adminBoard.setPostedBy((Integer) map.get("id"));
        adminMapper.submit(adminBoard);
    }

    @Override
    public List<ChangeRecord> getRecordInfo() {
        List<ChangeRecord> list = changeRecordMapper.getRecordInfo();
        return list;
    }
}
